package com.kuangstudy.service.set;

import com.kuangstudy.entity.User;
import com.kuangstudy.entity.Weibo;
import com.kuangstudy.utils.JsonUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/23 17:41
 */
@Service
@Log4j2
public class RandomService4 {

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String RANDOM_SET_KEY = "weibo:rand:set";

    // 1 : 初始化用户信息
    @PostConstruct
    public void initData() {
        log.info("将需要随机显示的榜单信息放入到redis集合中...");
        boolean flag = this.redisTemplate.hasKey(RANDOM_SET_KEY);
        if (!flag) {
            List<Weibo> initDataList = initDataList();
            initDataList.forEach(weibo -> this.redisTemplate.opsForSet().add(RANDOM_SET_KEY, JsonUtil.obj2String(weibo)));
        }
    }

    /**
     * 将需要随机的用户用户数据加载到集合中
     * 初始化100个用户，用于随机获取和推荐
     *
     * @return
     */
    private List<Weibo> initDataList() {
        List<Weibo> listdata = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            Weibo weibo = new Weibo();
            weibo.setName("榜单" + i);
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (int j = 1; j <= 10; j++) {
                Map<String, Object> map = new HashMap<>();
                map.put("title", "榜单" + i + "的数据");
                mapList.add(map);
            }
            weibo.setDatas(mapList);
            listdata.add(weibo);
        }
        return listdata;
    }

}
